package repository

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"net/url"
)

type ChatAPI struct {
	httpClient *http.Client
	apiKey     string
	apiURL     string
}

func NewChatAPI(apiKey, apiURL, proxyURL, proxyUser, proxyPassword string) *ChatAPI {
	proxyURI, err := url.Parse(proxyURL)
	if err != nil {
		fmt.Println("прокси шалит")
	}
	proxyURI.User = url.UserPassword(proxyUser, proxyPassword)

	transport := &http.Transport{
		Proxy: http.ProxyURL(proxyURI),
	}
	fmt.Println(transport)
	httpClient := &http.Client{
		Transport: transport,
	}

	return &ChatAPI{
		httpClient: httpClient,
		apiKey:     apiKey,
		apiURL:     apiURL,
	}
}

func (api *ChatAPI) SendRequest(payload []byte) ([]byte, error) {
	request, err := http.NewRequest("POST", api.apiURL, bytes.NewBuffer(payload))
	if err != nil {
		return nil, err
	}
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Authorization", "Bearer "+api.apiKey)

	response, err := api.httpClient.Do(request)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()

	responseBody, err := io.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}
	return responseBody, nil
}
